package com.lhkj.ct.base.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
  * <p>
  *     描述：模板替换工具
  * </p>
  */
public class TemplateUtil implements Serializable {

    /**
     * 模板替换  如: ${变量名} -> 变量名，tips 不修改源模板
     *
     * @param template
     *                  需要替换的字符串
     * @param regex
     *                  "\\$\\{([^\\}]+)\\}"是替换 ${}的
     *                  "\\{\\{([^\\}]+)\\}\\}"是替换{{}}的
     */
    public static String replaceTemplate(String template, String regex) {
        if (StringUtils.isBlank(template)) {
            return template;
        }
        Matcher matcher = matcher(template, regex);
        while (matcher.find()) {
            String group = matcher.group();
            template = template.replace(group, group.replaceAll(regex, "$1"));
        }
        return template;
    }

    /**
     * 模板解析
     *
     * @param template
     *                  需要替换的字符串
     * @param regex
     *                  "\\$\\{([^\\}]+)\\}"是替换 ${}的
     * @param properties
     * @return
     */
    public static String parseTemplate(String template, String regex, Map<String, Object> properties) {
        if (StringUtils.isBlank(template) || properties == null) {
            return template;
        }
        Matcher matcher = matcher(template, regex);
        while (matcher.find()) {
            String group = matcher.group();
            String replacement = group.replaceAll(regex, "$1");
            Object o = properties.get(group.replaceAll(regex, "$1"));
            if (o != null) {
                template = template.replace(group, String.valueOf(o));
            } else {
                template = template.replace(group, "");
            }
            template = template.replace(group, replacement);
        }
        return template;
    }

    /**
     * 正则匹配字符串
     *
     * @param text 匹配的文本
     */
    public static Matcher matcher(String text, String regex) {
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        return pattern.matcher(text);
    }
}
